package com.test.clyq.daoImpl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.springframework.dao.DataAccessException;

import com.test.clyq.dao.EntityItemDao;
import com.test.clyq.entity.EntityItem;
import com.test.clyq.entity.Users;
import com.test.dao.hibernate.BaseDaoHibernate;
import com.test.util.FormatExceptionStack;
import com.test.util.Pagination;
import com.test.util.SessionFactoryUtil;
import com.test.util.StringUtils;

/**
 * EntityItemDaoHibernate. <br>
 * 内容信息管理.
 * <p>
 * Copyright: Copyright (c) 2010-4-17 下午04:37:24
 * <p>
 * Company: 北京宽连十方数字技术有限公司
 * <p>
 * Author: liuxl@c-platform.com
 * <p>
 * Version: 1.0
 * <p>
 */
@SuppressWarnings("unchecked")
public class EntityItemDaoHibernate extends BaseDaoHibernate implements EntityItemDao {

	/**
	 * 新增内容信息
	 * 
	 * @param entityitem
	 *            内容实例
	 * @param user
	 *            用户实例
	 */
	public void addEntityItem(EntityItem entityitem, Users user) {
		this.log.info("新增内容信息start");
		try {
			saveOrUpdateItem(entityitem, user);
			this.log.debug("新增内容信息成功");
			this.log.info("新增内容信息end");
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]addEntityItem发生错误！\n" + FormatExceptionStack.formatException(e));
		}

	}

	/**
	 * 批量新增内容信息
	 * 
	 * @param list
	 *            内容实例列表
	 * @param user
	 *            用户实例
	 */
	public void addBAtch(List list, Users user) {
		this.log.info("新增内容信息start");
		try {
			saveOrUpdateBatchItems(list, user);
			this.log.debug("新增内容信息成功");
			this.log.info("新增内容信息end");
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]addEntityItem发生错误！\n" + FormatExceptionStack.formatException(e));
		}

	}

	/**
	 * 根据内容ID删除内容
	 * 
	 * @param id
	 *            内容ID
	 * @param user
	 *            用户实例
	 * @return true or false
	 */
	public boolean delEntityItemById(Long id, Users user) {
		this.log.info("根据内容ID删除内容start");
		try {
			EntityItem entityItem = (EntityItem) getItem(EntityItem.class, id);
			if (entityItem != null) {
				removeItem(EntityItem.class, id, user);
				this.log.debug("删除内容信息成功");
				this.log.info("根据内容ID删除内容end");
				return true;
			} else {
				this.log.debug("删除内容信息失败");
				return false;
			}
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]delEntityItemById发生错误！\n" + FormatExceptionStack.formatException(e));
			return false;
		}
	}

	/**
	 * 文章code
	 * 
	 * @return
	 */
	public String getEntityCode(Long categoryId) {
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {

			String sql = "select num_code from t_entity_num where entity_id=" + categoryId;
			SQLQuery query1 = session.createSQLQuery(sql);
			query1.addScalar("num_code", Hibernate.STRING);
			List<Object> list = query1.list();
			if (list != null && list.size() > 0) {
				String code = (String) list.get(0);
				return code;
			}
			return "";
		}
		catch (Exception e) {
			this.log.error("[CategoryTemp]getEntityTempLisgt发生错误！\n" + FormatExceptionStack.formatException(e));
		}
		finally {
			SessionFactoryUtil.isClose(session);
		}
		return null;
	}

	/***************************************************************************
	 * 根据栏目ID 或 父ID获取文章
	 * 
	 * @param categoryId
	 * @param pagination
	 * @param where
	 * @param order
	 * @return
	 */
	public List<EntityItem> getEntityItemByCategoryId(Long categoryId, Pagination pagination, String where, String order) {
		this.log.info("根据网站ID获得信息列表start");
		String sql = " from EntityItem as entityitem where entityitem.entityStatus=1 " + where + order;
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.createQuery("select count(*)" + sql);
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination.setTotalRows(((Integer) listCount.get(0)).intValue()); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}

			Query query1 = session.createQuery(sql.toString());
			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得内容信息列表end");
				return list;

			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<EntityItem>();
			}
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]getEntityItemByCategoryId发生错误！\n" + FormatExceptionStack.formatException(e));
			return new ArrayList<EntityItem>();
		}
		finally {
			SessionFactoryUtil.isClose(session);
		}
	}

	/***************************************************************************
	 * 根据taobaoId获取文章
	 * 
	 * @param taobaoId
	 * @return EntityItem
	 */
	public EntityItem getEntityItemByTaoBaoId(String taobaoId) {
		this.log.info("根据网站ID获得信息列表start");
		String sql = " from EntityItem as entityitem where entityitem.entityTaoBaoId=:tId";
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {

			Query query1 = session.createQuery(sql.toString());
			query1.setString("tId", taobaoId);
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得内容信息列表end");
				return (EntityItem) list.get(0);

			} else {
				this.log.debug("表中没有数据");
				return null;
			}
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]getEntityItemByCategoryId发生错误！\n" + FormatExceptionStack.formatException(e));
			return null;
		}
		finally {
			SessionFactoryUtil.isClose(session);
		}
	}

	/**
	 * 根据内容id获得内容信息
	 * 
	 * @param id
	 *            内容ID
	 * @return NLEntityItem 内容实体
	 */
	public EntityItem getEntityItemById(Long id) {
		this.log.info("根据内容ID获得内容信息start");
		try {
			EntityItem entityItem = (EntityItem) getItem(EntityItem.class, id);
			if (entityItem != null) {
				this.log.info("根据内容ID获得内容信息end");
				return entityItem;
			} else {
				this.log.info("根据内容ID获得内容信息end");
				return new EntityItem();
			}

		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]getEntityItemById发生错误！\n" + FormatExceptionStack.formatException(e));
			return new EntityItem();
		}
	}

	/**
	 * 根据栏目ID获得内容信息列表（分页使用）
	 * 
	 * @param categoryId
	 *            栏目ID
	 * @return 内容信息列表结果集合
	 */
	public List<EntityItem> getEntityItemListByCategoryId(Long categoryId, Pagination pagination) {
		this.log.info("根据网站ID获得信息列表start");
		String sql = " from EntityItem as entityitem where entityitem.entityCategoryId=:categoryid and entityitem.entityStatus=1 order by entityitem.isTop desc,entityitem.id desc";
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			System.err.println("select count(*)" + sql);
			Query query = session.createQuery("select count(*)" + sql);
			query.setLong("categoryid", categoryId);
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination.setTotalRows(((Integer) listCount.get(0)).intValue()); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}
			Query query1 = session.createQuery(sql.toString());
			query1.setLong("categoryid", categoryId);
			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得内容信息列表end");
				return list;

			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<EntityItem>();
			}
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]getEntityItemByCategoryId发生错误！\n" + FormatExceptionStack.formatException(e));
			return new ArrayList<EntityItem>();
		}
		finally {
			SessionFactoryUtil.isClose(session);
		}
	}

	/**
	 * 根据栏目ID获得内容信息列表（分页使用）
	 * 
	 * @param categoryId
	 *            栏目ID
	 * @return 内容信息列表结果集合
	 */
	public List<EntityItem> getEntityItemListByCategoryId(Long categoryId, Pagination pagination, String where, String order) {
		this.log.info("根据网站ID获得信息列表start");
		String sql = " from EntityItem as entityitem where entityitem.entityCategoryId=:categoryid and entityitem.entityStatus=1 " + where + order;
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.createQuery("select count(*)" + sql);
			query.setLong("categoryid", categoryId);
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination.setTotalRows(((Integer) listCount.get(0)).intValue()); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}

			Query query1 = session.createQuery(sql.toString());
			query1.setLong("categoryid", categoryId);
			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得内容信息列表end");
				return list;

			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<EntityItem>();
			}
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]getEntityItemByCategoryId发生错误！\n" + FormatExceptionStack.formatException(e));
			return new ArrayList<EntityItem>();
		}
		finally {
			SessionFactoryUtil.isClose(session);
		}
	}

	public List<EntityItem> getEntityItemListByKeyWord(String keyword, Pagination pagination) {
		this.log.info("根据关键词查找匹配列表start");
		String sql = " from EntityItem as entityitem where entityitem.entityStatus=1 order by entityitem.id desc";
		if (!StringUtils.isEmpty(keyword)) {
			sql = " from EntityItem as entityitem where entityitem.entityStatus=1 and entityitem.entityName like '%" + keyword
			        + "%' or entityitem.entityArticleKeyword like '%" + keyword + "%' order by entityitem.id desc";
		}
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.createQuery("select count(*)" + sql);
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination.setTotalRows(((Integer) listCount.get(0)).intValue()); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}

			Query query1 = session.createQuery(sql.toString());
			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("根据关键词查找匹配列表成功");
				this.log.info("根据关键词查找匹配列表end");
				return list;

			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<EntityItem>();
			}
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]getEntityItemListByKeyWord！\n" + FormatExceptionStack.formatException(e));
			return new ArrayList<EntityItem>();
		}
		finally {
			SessionFactoryUtil.isClose(session);
		}
	}

	/**
	 * 根据一级栏目ID获得所有二级栏目的置顶内容信息列表（分页使用）
	 * 
	 * @param categoryId
	 * @return 内容信息列表结果集合
	 */
	public List<EntityItem> getEntityItemListByParentCategoryId(Long categoryId, Pagination pagination, String where, String order) {
		this.log.info("根据一级栏目ID获得所有二级栏目的置顶内容信息列表start");
		String sql = " from EntityItem as entityitem where entityitem.entityCategoryId =:parentId " + where + order;

		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.createQuery("select count(*)" + sql);
			query.setLong("parentId", categoryId);
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination.setTotalRows(((Integer) listCount.get(0)).intValue()); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}

			Query query1 = session.createQuery(sql.toString());
			query1.setLong("parentId", categoryId);
			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("根据一级栏目ID获得所有二级栏目的置顶内容信息列表成功");
				this.log.info("根据一级栏目ID获得所有二级栏目的置顶内容信息列表end");
				return list;

			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<EntityItem>();
			}
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]getEntityItemListByParentCategoryId！\n" + FormatExceptionStack.formatException(e));
			return new ArrayList<EntityItem>();
		}
		finally {
			SessionFactoryUtil.isClose(session);
		}
	}

	/**
	 * 根据条件 获得内容信息列表（分页使用）
	 * 
	 * @return 内容信息列表结果集合
	 */
	public List<EntityItem> getEntityItemListByWhere(Pagination pagination, String where, String order) {
		this.log.info("根据网站ID获得信息列表start");
		String sql = " from EntityItem as entityitem where entityitem.entityStatus=1 " + where + order;
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.createQuery("select count(*)" + sql);
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination.setTotalRows(((Integer) listCount.get(0)).intValue()); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}

			Query query1 = session.createQuery(sql.toString());
			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得内容信息列表end");
				return list;

			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<EntityItem>();
			}
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]getEntityItemByCategoryId发生错误！\n" + FormatExceptionStack.formatException(e));
			return new ArrayList<EntityItem>();
		}
		finally {
			SessionFactoryUtil.isClose(session);
		}
	}

	/**
	 * 获取期刊栏目下的成品
	 * 
	 * @param categoryId
	 *            栏目ID
	 * @return 内容信息列表结果集合
	 */
	public List<EntityItem> getEntityItemListForJournals(Long categoryId, Pagination pagination) {
		this.log.info("根据网站ID获得信息列表start");
		String sql = " from EntityItem as entityitem where entityitem.entityCategoryId=:categoryid and entityitem.entityStatus=1 and entityitem.mmsFirst = 1 order by entityitem.mmsWeight desc,entityitem.id desc";
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.createQuery("select count(*)" + sql);
			query.setLong("categoryid", categoryId);
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination.setTotalRows(((Integer) listCount.get(0)).intValue()); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}

			Query query1 = session.createQuery(sql.toString());
			query1.setLong("categoryid", categoryId);
			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得内容信息列表end");
				return list;

			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<EntityItem>();
			}
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]getEntityItemByCategoryId发生错误！\n" + FormatExceptionStack.formatException(e));
			return new ArrayList<EntityItem>();
		}
		finally {
			SessionFactoryUtil.isClose(session);
		}
	}

	/**
	 * 根据网站ID获得回收站信息列表（分页使用）
	 * 
	 * @return 回收站信息列表结果集合
	 */
	public List<EntityItem> getRecycleBinListByWebsiteId(Pagination pagination) {
		this.log.info("根据网站ID获得回收站信息列表start");
		String sql = " from EntityItem as nlentityitem  where nlentityitem.entityStatus=0 order by nlentityitem.entityCreatetime  desc";
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query = session.createQuery("select count(*)" + sql);
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination.setTotalRows(((Integer) listCount.get(0)).intValue()); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}

			Query query1 = session.createQuery(sql.toString());
			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得回收站信息列表end");
				return list;

			} else {
				this.log.debug("表中没有数据");
				return null;
			}
		}
		catch (DataAccessException e) {
			this.log.error("[NLEntityItem]getNLRecycleBinListByWebsiteId发生错误！\n" + FormatExceptionStack.formatException(e));
			return null;
		}
		finally {
			SessionFactoryUtil.isClose(session);
		}
	}

	public List<EntityItem> getRelateList(Long entityItemId) {
		this.log.info("根据原文章id查找相关文章的列表start");
		String sql = " from EntityItem as entityitem where entityitem.entityStatus=1 and (entityitem.id=:entityItemId or entityitem.sourceId=:sourceId)";
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			Query query1 = session.createQuery(sql.toString());
			query1.setLong("entityItemId", entityItemId);
			query1.setLong("sourceId", entityItemId);
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得内容信息列表end");
				return list;

			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<EntityItem>();
			}
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]getEntityItemByCategoryId发生错误！\n" + FormatExceptionStack.formatException(e));
			return new ArrayList<EntityItem>();
		}
		finally {
			SessionFactoryUtil.isClose(session);
		}

	}

	public List<EntityItem> getVisitEntityItemLogByTime(Pagination pagination, String startTime, String endTime) {
		this.log.info("根据网站ID获得信息列表start");
		System.out.println(startTime + "==" + endTime);
		String sql = " from EntityItem as entityitem where entityitem.entityStatus=1 and entityitem.entityCreatetime > '" + startTime
		        + "' and entityitem.entityCreatetime < '" + endTime + "' order by entityitem.browseCount desc,entityitem.id desc";
		SessionFactory sessionFactory = getHibernateTemplate().getSessionFactory();
		Session session = sessionFactory.openSession();
		try {
			System.err.println("select count(*)" + sql);
			Query query = session.createQuery("select count(*)" + sql);
			List listCount = query.list();
			if (listCount != null && !listCount.isEmpty()) {
				pagination.setTotalRows(((Integer) listCount.get(0)).intValue()); // 获得记录总数
			} else {
				pagination.setTotalRows(0);
			}

			Query query1 = session.createQuery(sql.toString());

			query1.setFirstResult(pagination.getStartIndex());
			query1.setMaxResults(pagination.getNumPerPage());
			List list = query1.list();
			if (list != null && list.size() > 0) {
				this.log.debug("获得列表数据");
				this.log.info("获得内容信息列表end");
				return list;

			} else {
				this.log.debug("表中没有数据");
				return new ArrayList<EntityItem>();
			}
		}
		catch (DataAccessException e) {
			this.log.error("[EntityItem]getEntityItemByCategoryId发生错误！\n" + FormatExceptionStack.formatException(e));
			return new ArrayList<EntityItem>();
		}
		finally {
			SessionFactoryUtil.isClose(session);
		}
	}

	public void merge(EntityItem entityitem, Users user) {

		this.log.info("保存或更新内容信息start");
		try {
			getHibernateTemplate().merge(entityitem);
			this.log.debug("保存内容信息成功");
			this.log.info("保存或更新内容信息end");
		}
		catch (Exception e) {
			this.log.error("[EntityItem]merge发生错误！\n" + FormatExceptionStack.formatException(e));
		}

	}

	/**
	 * 保存或更新内容信息
	 * 
	 * @param entityitem
	 *            内容实例
	 * @param user
	 *            用户实例
	 */
	public void saveOrUpdate(EntityItem entityitem, Users user) {
		this.log.info("保存或更新内容信息start");
		try {
			saveOrUpdateItem(entityitem, user);
			// getHibernateTemplate().saveOrUpdate(entityitem);
			this.log.debug("保存内容信息成功");
			this.log.info("保存或更新内容信息end");
		}
		catch (Exception e) {
			this.log.error("[EntityItem]saveOrUpdate发生错误！\n" + FormatExceptionStack.formatException(e));
		}

	}

	@Override
	public List<EntityItem> getAllEntityItems() {
		// TODO Auto-generated method stub
		return null;
	}
}
